# -*- coding: utf-8 -*-
import time
import json
import logging
import datetime
from django import forms
from django import template
from django.db.models import Q
from django.conf import settings
from django.core.cache import cache
from django.shortcuts import render
from django.template import Context, loader
from django.http import HttpResponse, Http404
from django.core.paginator import Paginator
from apps.models import Nav, Carousel, News, Product, SysConfig, SubTitle, \
    NavImages
from django.shortcuts import render, render_to_response
from django.views.decorators.csrf import csrf_exempt
from django.core.urlresolvers import reverse
from django.views.generic import View, TemplateView, ListView, DetailView
from apps.models import *
from django.core.paginator import Paginator

logger = logging.getLogger(__name__)

class BaseMixin(object):
    def get_context_data(self, *args, **kwargs):
        context = super(BaseMixin, self).get_context_data(**kwargs)
        proxy = self.request.proxy
        try:
            # 网站标题等内容
            context['website_info'] = proxy.all(SysConfig)[0]
        except Exception as e:
            logger.error(u'[BaseMixin]加载基本信息出错')

        # TODO底部栏
        context['wx_images'] = proxy.all(WxImage)
        # 导航条
        context['nav_list'] = proxy.all(Nav).order_by('priority')
        # 设置语言
        context['language'] = self.request.language

        return context


class IndexView(BaseMixin, TemplateView):
    template_name = 'index.html'
    paginate_by = 4  # 显示的条数

    def get_context_data(self, **kwargs):
        proxy = self.request.proxy
        # 轮播
        kwargs['carousel_page_list'] = Carousel.objects.all()
        # 企业简介
        kwargs['company_list'] = proxy.all(CompanyImage)
        # 行业新闻
        kwargs['news_list'] = proxy.all(News).filter(types=1)[:self.paginate_by]
        # 公司新闻 图片
        kwargs['news_img'] = proxy.all(News).filter(types=0, img__isnull=False)[:self.paginate_by]
        # 产品
        try:
            kwargs['product_list'] = proxy.all(Product)
            product_url = reverse("product_view")
            kwargs['product_nav'] = proxy.all(Nav).get(url__url=product_url)
            new_url = reverse("new_view")
            kwargs['new_nav'] = proxy.all(Nav).get(url__url=new_url)
            # 企业实力
            subtitle_url = "/common/message/"
            subtitle_from_nav = proxy.all(Nav).get(url__url=subtitle_url)
            kwargs['strength_nav'] = subtitle_from_nav
            if subtitle_from_nav:
                kwargs['subtitle_list'] = proxy.all(SubTitle).filter(nav=subtitle_from_nav)[:self.paginate_by]
        except Exception as e:
            logging.error("[IndexView] 信息加载出错")
        kwargs['url'] = '/'

        data = super().get_context_data(**kwargs)
        return data


class CommonView(BaseMixin, TemplateView):
    """ 公用类型的视图 实力 服务
    """

    template_name = 'common.html'

    def get_context_data(self, **kwargs):
        slug = self.kwargs.get('slug')
        nav_id = self.request.GET.get('nav_id')
        subtitle_id = self.request.GET.get('subtitle')
        proxy = self.request.proxy
        # 子标题
        subtitle_lists = proxy.filter(SubTitle, nav_id=nav_id)
        kwargs['subtitle_lists'] = subtitle_lists
        kwargs['carousel_page_list'] = NavImages.objects.filter(nav_id=nav_id)
        # 详情
        if slug == 'honor':
            self.template_name = 'honor.html'
            # 公司荣誉 length 8
            kwargs['honor_objects'] = Paginator(Honor, 8)
            # 当前位置
            kwargs['location'] = 'honor'
        elif slug == 'service':
            # 服务
            self.template_name = 'job.html'
            kwargs['job_objects'] = Paginator(Jobs, job_num)
            kwargs['location'] == 'job'
        elif slug == 'message':
            # 实力
            self.template_name = 'message.html'
            kwargs['url'] = '/common/message/'
            try:
                if not subtitle_id:
                    kwargs['local'] = subtitle_lists[0]
                else:
                    kwargs['local'] = subtitle_lists.filter(pk=subtitle_id)[0]
            except Exception as e:
                logger.error(u'[CommonView]加载基本信息出错')
        elif slug == 'job':
            kwargs['url'] = '/common/job/'
            if not subtitle_id:
                kwargs['local'] = subtitle_lists[0]
            else:
                kwargs['local'] = subtitle_lists.filter(pk=subtitle_id)[0]
        else:
            raise Http404

        return super().get_context_data(**kwargs)

# 新闻、产品
class NewsList(BaseMixin, ListView):
    paginate_by = 6
    template_name = "news/news_list.html"
    model = News
    def get_context_data(self, **kwargs):
        news_type = int(self.request.GET.get('news_type', 0))
        nav_id = self.request.GET.get('nav_id')
        kwargs['localnav'] = Nav.objects.get(pk=nav_id)
        kwargs['local_news_type'] = news_type
        kwargs['local_news_value'] = News.NEWS.get(news_type)
        kwargs['carousel_page_list'] = NavImages.objects.filter(nav_id=nav_id)
        kwargs['subtitle_lists'] = News.NEWS

        return super(NewsList, self).get_context_data(**kwargs)

    def get_queryset(self):
        news_type = int(self.request.GET.get('news_type', 0))
        return News.objects.filter(types=news_type).order_by('-img')



class CaseList(BaseMixin, ListView):
    paginate_by = 6
    template_name = "case_list.html"
    model = Case
    def get_context_data(self, **kwargs):
        nav_id = self.request.GET.get('nav_id')
        kwargs['localnav'] = Nav.objects.get(pk=nav_id)
        kwargs['carousel_page_list'] = NavImages.objects.filter(nav_id=nav_id)

        return super().get_context_data(**kwargs)


class NewsDetailed(BaseMixin, DetailView):
    template_name = "news/news_detailed.html"
    model = News

    def addViewTimes(self, request):
        # 统计文章的访问访问次数
        if 'HTTP_X_FORWARDED_FOR' in request.META:
            ip = request.META['HTTP_X_FORWARDED_FOR']
        else:
            ip = request.META['REMOTE_ADDR']
        self.cur_user_ip = ip

        url_path = request.path
        # 获取15*60s时间内访问过这篇新闻的所有ip
        visited_ips = cache.get(url_path, [])

        # 如果ip不存在就把文章的浏览次数+1
        if ip not in visited_ips:
            self.object.view_times += 1
            self.object.save()
            visited_ips.append(ip)

            # 更新缓存
            cache.set(url_path, visited_ips, 15*60)

    def get_context_data(self, **kwargs):
        proxy = self.request.proxy
        news_type = int(self.request.GET.get('news_type', 0))
        nav_id = self.request.GET.get('nav_id')
        kwargs['localnav'] = Nav.objects.get(pk=nav_id)
        kwargs['local_news_type'] = news_type
        kwargs['local_news_value'] = News.NEWS.get(news_type)
        kwargs['carousel_page_list'] = NavImages.objects.filter(nav_id=nav_id)
        kwargs['subtitle_lists'] = News.NEWS
        # 感兴趣的文章
        kwargs['interested_news'] = proxy.filter(News).order_by("view_times")[:3]
        # 上一条 下一条 新闻
        new_list = proxy.filter(News, types=self.object.types)
        new_list_index = [i.pk for i in new_list]
        cur_pk = new_list_index.index(self.object.pk)

        # 上一条
        if not cur_pk <= 0:
            previous_pk = new_list_index[cur_pk-1]
            kwargs['previous_obj'] = News.objects.get(pk=previous_pk)
        # 下一条
        if not cur_pk >= len(new_list_index)-1:
            next_pk = new_list_index[cur_pk+1]
            kwargs['next_obj'] = News.objects.get(pk=next_pk)

        self.addViewTimes(self.request)

        return super().get_context_data(**kwargs)

class ProductList(BaseMixin, ListView):
    paginate_by = 9
    template_name = "product/product_list.html"
    model = Product

    def get_context_data(self, **kwargs):
        proxy = self.request.proxy
        nav_id = self.request.GET.get('nav_id')
        type_id = self.request.GET.get('type_id')
        kwargs['localnav'] = Nav.objects.get(pk=nav_id)
        kwargs['carousel_page_list'] = NavImages.objects.filter(nav_id=nav_id)
        kwargs['subtitle_lists'] = proxy.all(ProductTypes)
        # 当前的子标题
        if not type_id:
            kwargs['local_subtitle'] = proxy.all(ProductTypes)[0]
        else:
            kwargs['local_subtitle'] = proxy.all(ProductTypes).get(pk=type_id)

        return super(ProductList, self).get_context_data(**kwargs)

    def get_queryset(self):
        proxy = self.request.proxy
        type_id = self.request.GET.get('type_id')
        if not type_id:
            current_obj = proxy.all(ProductTypes)[0]
        else:
            current_obj = ProductTypes.objects.get(pk=int(type_id))

        return proxy.all(Product).filter(types=current_obj)


class ProductDetailed(BaseMixin, DetailView):
    template_name = "product/product_detailed.html"
    model = Product
    def get_context_data(self, **kwargs):
        proxy = self.request.proxy
        nav_id = self.request.GET.get('nav_id')
        type_id = self.request.GET.get('type_id')
        kwargs['localnav'] = Nav.objects.get(pk=nav_id)
        kwargs['carousel_page_list'] = NavImages.objects.filter(nav_id=nav_id)
        kwargs['subtitle_lists'] = proxy.all(ProductTypes)
        # 当前的子标题
        if not type_id:
            kwargs['local_subtitle'] = proxy.all(ProductTypes)[0]
        else:
            kwargs['local_subtitle'] = proxy.all(ProductTypes).get(pk=type_id)
        # 相关的产品
        kwargs['related_products'] = proxy.filter(Product, types=self.object.types)[:3]
        # 上一条 下一条 产品
        product_list = proxy.filter(Product, types=self.object.types)
        product_list_index = [i.pk for i in product_list]
        cur_pk = product_list_index.index(self.object.pk)

        # 上一条
        if not cur_pk <= 0:
            previous_pk = product_list_index[cur_pk-1]
            kwargs['previous_obj'] = Product.objects.get(pk=previous_pk)
        # 下一条
        if not cur_pk >= len(product_list_index)-1:
            next_pk = product_list_index[cur_pk+1]
            kwargs['next_obj'] = Product.objects.get(pk=next_pk)



        return super().get_context_data(**kwargs)




class ContactView(BaseMixin, TemplateView):
    """ 地图和留言
    """
    template_name = "contact.html"
    def get_context_data(self, **kwargs):
        nav_id = self.request.GET.get('nav_id')
        slug = self.kwargs.get('slug')
        proxy = self.request.proxy
        # 子标题
        if nav_id:
            kwargs['localnav'] = Nav.objects.get(pk=nav_id)
            kwargs['carousel_page_list'] = NavImages.objects.filter(nav_id=nav_id)
        kwargs['subtitle_lists'] = [("map", "百度地图"), ("message", "在线留言")]
        if slug == "map":
            kwargs['subtitle'] = "百度地图"
            kwargs['include_html'] = "./include/map.html"
        elif slug == "message":
            kwargs['url'] = '/contact/message/'
            kwargs['subtitle'] = "在线留言"
            kwargs['include_html'] = "./include/message.html"
        else:
            raise Http404

        return super().get_context_data(**kwargs)

@csrf_exempt
def leaveMessage(request):
    """ 留言
    """
    data = dict(request.POST)
    if 'HTTP_X_FORWARDED_FOR' in request.META:
        ip = request.META['HTTP_X_FORWARDED_FOR']
    else:
        ip = request.META['REMOTE_ADDR']
    result = {'code': 0, 'result': 'ok'}
    try:
        _data = {}
        _data['email'] = data['Email']
        _data['qq'] = data['QQ']
        _data['content'] = data['content']
        _data['nickname'] = data['name']
        _data['telephone'] = data['phone']
        _data['title'] = data['title']
    except Exception as e:
        logger.error(u'[leaveMessage] 参数错误')
        result['result'] = '参数错误'
        result['code'] = 500
    ip_lists = cache.get('leavemessage', [])
    if ip not in ip_lists:
        l = LeaveMessage(**_data)
        l.save()
        ip_lists.append(ip)
        cache.set('leavemessage', ip_lists, 15*60)
    else:
        result['result'] = '您已留言成功，请勿重复留言'
        result['code'] = 500

    return HttpResponse(json.dumps(result), content_type='application/json')




# 公司荣誉
class HonorListView(BaseMixin, ListView):
    paginate_by = 6
    template_name = "honor/honor_list.html"
    model = Honor
    def get_context_data(self, **kwargs):
        nav_id = self.request.GET.get('nav_id')
        subtitle_id = self.request.GET.get('subtitle')
        proxy = self.request.proxy
        # 子标题
        subtitle_lists = proxy.filter(SubTitle, nav_id=nav_id)
        kwargs['subtitle_lists'] = subtitle_lists
        kwargs['carousel_page_list'] = NavImages.objects.filter(nav_id=nav_id)
        kwargs['tag'] = 'honor'

        return super().get_context_data(**kwargs)
